package cn.microven.mindmap.oprations;

import cn.microven.mindmap.components.node.AbstractMapNode;
import cn.microven.mindmap.struture.MindMap;

import java.time.Duration;
import java.time.Instant;

public class ChangeFontSizeOperation implements Operation {

    private int oldValue;

    private int newValue;

    private AbstractMapNode node;

    private Instant createdAt;

    public ChangeFontSizeOperation(int o, int n,AbstractMapNode node) {
        oldValue = o;
        newValue = n;
        createdAt = Instant.now();
        this.node = node;
    }

    @Override
    public void start(boolean isRedo) {
        node.setFontSize(newValue);

        if (!isRedo) {
            if (MindMap.getLastOperation() != null) {
                if (MindMap.getLastOperation().getClass() == this.getClass()) {
                    ChangeFontSizeOperation old = (ChangeFontSizeOperation) MindMap.getLastOperation();
                    this.setOldValue(old.getOldValue());
                    MindMap.getInstance().getOperations().remove(old);
                    MindMap.getInstance().setOprIndex(MindMap.getInstance().getOprIndex()-1);
                }
            }
            MindMap.addOperation(this);
        }
    }

    @Override
    public void undo() {
        node.setFontSize(oldValue);
        node.layout();
    }

    public boolean isSameOperation(ChangeFontSizeOperation c) {
        return node == c.getNode() && Duration.between(c.getCreatedAt(), this.getCreatedAt()).toMillis() <= 500;
    }

    public void setNewValue(int newValue) {
        this.newValue = newValue;
    }

    public int getNewValue() {
        return newValue;
    }

    public int getOldValue() {
        return oldValue;
    }

    public Instant getCreatedAt() {
        return createdAt;
    }

    public AbstractMapNode getNode() {
        return node;
    }

    public void setOldValue(int oldValue) {
        this.oldValue = oldValue;
    }

    public void setNode(AbstractMapNode node) {
        this.node = node;
    }

    public void                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 setCreatedAt(Instant createdAt) {
        this.createdAt = createdAt;
    }
}
